# -*- coding: utf-8  -*-
#!/usr/local/bin/python

__author__ = 'jian.yao'

from django.db.models import Q
from misc.backend import BaseManager
from cm.privilege.models import Channel, Role, RolePermission, AdminRole
from cm.privilege.constants import ChannelOrderType, RoleOrderType, RolePermissionOrderType, AdminRoleOrderType
from datetime import datetime

class ChannelManager(BaseManager):

    def __init__(self):
        _order_type = ChannelOrderType
        BaseManager.__init__(self, _model=Channel, _order_type=_order_type)

    def __save__(self, _object, _commit = True, **kargs):
        if not _object:
            return None

        if '_id' in kargs:
            _object.id = kargs['_id']

        if '_name' in kargs:
            _object.name = kargs['_name']

        if '_key' in kargs:
            _object.key = kargs['_key']

        if '_expiration' in kargs:
            _object.expiration = kargs['_expiration']

        if '_description' in kargs:
            _object.description = kargs['_description']

        if '_domain' in kargs:
            _object.domain = kargs['_domain']

        if '_creator' in kargs:
            _object.creator = kargs['_creator']

        if '_create_time' in kargs:
            _object.create_time = kargs['_create_time']

        if '_last_editor' in kargs:
            _object.last_editor = kargs['_last_editor']

        if '_last_update' in kargs:
            _object.last_update = kargs['_last_update']

        if _commit:
            _object.save()

        return _object

    def query(self, _query_set = None, **kwargs):
        _order_by = kwargs.pop("_order_by", None)
        _objects = BaseManager.query(self, _query_set = _query_set, **kwargs)

        _query = Q()

        if '_name' in kwargs:
            _query = _query & Q(name__icontains = kwargs.pop("_name"))
        if '_description' in kwargs:
            _query = _query & Q(description__icontains = kwargs.pop("_description"))
        if '_domain' in kwargs:
            _query = _query & Q(domain__icontains = kwargs.pop("_domain"))
        if '_creator' in kwargs:
            _query = _query & Q(creator = kwargs.pop('_creator'))
        if '_last_editor' in kwargs:
            _query = _query & Q(last_editor = kwargs.pop('_last_editor'))
        if '_create_time1' in kwargs:
            _query = _query & Q(create_time__gte = kwargs.pop('_create_time1'))
        if '_create_time2' in kwargs:
            _query = _query & Q(create_time__lte = kwargs.pop('_create_time2'))
        if '_last_update1' in kwargs:
            _query = _query & Q(last_update__gte = kwargs.pop('_last_update1'))
        if '_last_update2' in kwargs:
            _query = _query & Q(last_update__lte = kwargs.pop('_last_update2'))
        if '_expiration' in kwargs:
            _query = _query & Q(expiration = kwargs.pop("_expiration"))

        if _query:
            _objects = _objects.filter(_query)

        if _order_by:
            _objects = self.ordered(_query_set = _objects, _order_by = _order_by)

        return _objects

    def query_keywords(self, _query_set = None, _keywords = None, **kwargs):
        if not _keywords:
            return _query_set

        _objects = self.query(_query_set=_query_set, **kwargs)

        __keywords = []

        if isinstance(_keywords, basestring):
            __keywords = _keywords.strip().split(' ')
        elif isinstance(_keywords, list):
            __keywords = _keywords

        _query = Q()

        for _item in __keywords:
            _query = _query | Q(name__icontains = _item)
        for _item in __keywords:
            _query = _query | Q(description__icontains = _item)

        if _query:
            _objects = _objects.filter(_query)

        return _objects

    def query_config_dict(self, **kwargs):
        _result = []
        _server_set = self.query(**kwargs)
        if _server_set:
            _result = list(_server_set.values())

            for _item in _result:
                #encode to utf-8
                for k in _item:
                    if isinstance(_item[k], unicode):
                        _item[k] = _item[k].encode("utf-8")

                _item["channel"] = _item.pop("name", None)
                _item["expiration"] = datetime.strftime(_item["expiration"], "%Y-%m-%d %H:%M:%S")
                if _item.get("domain", ""):
                    _item["domain"] = _item.pop("domain", "").split("|")

        return _result

class RoleManager(BaseManager):
    def __init__(self):
        _order_type = RoleOrderType
        BaseManager.__init__(self, _model=Role, _order_type=_order_type)

    def __save__(self, _object, _commit = True, **kwargs):
        if not _object:
            return None

        if '_id' in kwargs:
            _object.id = kwargs['_id']
        if '_channel_id' in kwargs:
            _object.channel_id = kwargs['_channel_id']
        if '_name' in kwargs:
            _object.name = kwargs['_name']
        if '_is_default' in kwargs:
            _object.is_default = kwargs['_is_default']
        if '_description' in kwargs:
            _object.description = kwargs['_description']
        if '_creator' in kwargs:
            _object.creator = kwargs['_creator']
        if '_create_time' in kwargs:
            _object.create_time = kwargs['_create_time']
        if '_last_editor' in kwargs:
            _object.last_editor = kwargs['_last_editor']
        if '_last_update' in kwargs:
            _object.last_update = kwargs['_last_update']

        if _commit:
            _object.save()

        return _object

    def query(self, _query_set = None, **kargs):
        _order_by = kargs.pop("_order_by", None)

        _objects = BaseManager.query(self, _query_set = _query_set, **kargs)

        _query = Q()
        if '_channel_id' in kargs:
            _query = _query & Q(channel_id = kargs.pop("_channel_id"))
        if '_name' in kargs:
            _query = _query & Q(name__icontains = kargs.pop("_name"))
        if '_is_default' in kargs:
            _query = _query & Q(is_default = kargs.pop("_is_default"))
        if '_description' in kargs:
            _query = _query & Q(description__icontains = kargs.pop("_description"))
        if '_create' in kargs:
            _query = _query & Q(creator = kargs.pop("_creator"))
        if '_last_editor' in kargs:
            _query = _query & Q(last_editor = kargs.pop("_last_editor"))
        if '_create_time1' in kargs:
            _query = _query & Q(create_time__gte = kargs.pop("_create_time1"))
        if '_create_time2' in kargs:
            _query = _query & Q(create_time__lte = kargs.pop("_create_time2"))
        if '_last_update1' in kargs:
            _query = _query & Q(last_update__gte = kargs.pop("_last_update1"))
        if '_last_update2' in kargs:
            _query = _query & Q(last_update__lte = kargs.pop("_last_update2"))

        if _query:
            _objects = _objects.filter(_query)

        if _order_by:
            _objects = self.ordered(_query_set = _objects, _order_by = _order_by)

        return _objects

    def query_keywords(self, _query_set = None, _keywords = None, **kargs):
        if not _keywords:
            return _query_set

        _objects = self.query(_query_set=_query_set, **kargs)

        __keywords = []
        if isinstance(_keywords, basestring):
            __keywords = _keywords.strip().split(' ')
        elif isinstance(_keywords, list):
            __keywords = _keywords

        _query = Q()

        for _item in __keywords:
            _query = _query | Q(name__icontains = _item)
        for _item in __keywords:
            _query = _query | Q(description__icontains = _item)

        if _query:
            _objects = _objects.filyer(_query)

        return _objects

    def query_config_dict(self, **kargs):
        _result = []
        _server_set = self.query(**kargs)
        if _server_set:
            _result = list(_server_set.values())
            for _item in _result:
                _item["channel"] = _item.pop("channel_id", None)
                _item["permission"] = []

            _rp_manager = RolePermissionManager()
            _rps = _rp_manager.query()
            for __rp in _rps:
                _role = __rp.role_id
                _permission = (__rp.module, __rp.method)
                for _item in _result:
                    for k in _item:
                        if isinstance(_item[k], unicode):
                            _item[k] = _item[k].encode("utf-8")
                        if _role == _item.get("id", None):
                            _item["permission"].append(_permission)
        return _result

class RolePermissionManager(BaseManager):
    def __init__(self):
        _order_type = RolePermissionOrderType
        BaseManager.__init__(self, _model=RolePermission, _order_type=_order_type)

    def __save__(self, _object, _commit = True, **kwargs):
        if not _object:
            return None

        if '_id' in kwargs:
            _object.id = kwargs['_id']
        if '_role_id' in kwargs:
            _object.role_id = kwargs['_role_id']
        if '_module' in kwargs:
            _object.module = kwargs['_module']
        if '_method' in kwargs:
            _object.method = kwargs['_method']
        if '_last_editor' in kwargs:
            _object.last_editor = kwargs['_last_editor']
        if '_last_update' in kwargs:
            _object.last_update = kwargs['_last_update']

        if _commit:
            _object.save()

        return _object

    def query(self, _query_set = None, **kargs):
        _order_by = kargs.pop('_order_by', None)
        _objects = BaseManager.query(self, _query_set = _query_set, **kargs)

        _query = Q()
        if '_role_id' in kargs:
            _query = _query & Q(role_id = kargs.pop('_role_id'))
        if '_module' in kargs:
            _query = _query & Q(module = kargs.pop("_module"))
        if '_method' in kargs:
            _query = _query & Q(method = kargs.pop("_method"))
        if '_last_editor' in kargs:
            _query = _query & Q(last_editor = kargs.pop("_last_editor"))
        if '_last_update1' in kargs:
            _query = _query & Q(last_update__gte = kargs.pop("_last_update1"))
        if '_last_update2' in kargs:
            _query = _query & Q(last_update__lte = kargs.po("_last_update2"))
        if '_usr_id' in kargs:
            _query = _query & Q(role__adminrole__user_id = kargs.pop("_user_id"))

        if _query:
            _objects = _objects.filter(_query)

        if _order_by:
            _objects = self.ordered(_query_set = _objects, _order_by = _order_by)

        return _objects

class AdminRoleManager(BaseManager):
    def __init__(self):
        _order_type = AdminRoleOrderType
        BaseManager.__init__(self, _model=AdminRole, _order_type=_order_type)

    def __save__(self, _object, _commit = True, **kwargs):
        if not _object:
            return None

        if '_id' in kwargs:
            _object.id = kwargs['_id']
        if '_role_id' in kwargs:
            _object.role_id = kwargs['_role_id']
        if '_user_id' in kwargs:
            _object.user_id = kwargs['_user_id']
        if '_last_editor' in kwargs:
            _object.last_editor = kwargs['_last_editor']
        if '_last_update' in kwargs:
            _object.last_update = kwargs['_last_update']

        if _commit:
            _object.save()

        return _object

    def query(self, _query_set = None, **kwargs):
        _order_by = kwargs.pop("_order_by", None)
        _objects = BaseManager.query(self, _query_set = _query_set, **kwargs)

        _query = Q()
        if '_role_id' in kwargs:
            _query = _query & Q(role_id = kwargs.pop("_role_id"))
        if '_user_id' in kwargs:
            _query = _query & Q(user_id = kwargs.pop("_user_id"))
        if '_last_editor' in kwargs:
            _query = _query & Q(last_editor = kwargs.pop("_last_editor"))
        if '_last_update1' in kwargs:
            _query = _query & Q(last_update__gte = kwargs.pop("_last_update1"))
        if '_last_update2' in kwargs:
            _query = _query & Q(last_update__lte = kwargs.pop("_last_update2"))

        if _query:
            _objects = _objects.filter(_query)

        if _order_by:
            _objects = self.ordered(_query_set = _objects, _order_by = _order_by)

        return _objects